package com.fhcodeintegration.demo06ai.service.impl;


import com.fhcodeintegration.demo06ai.service.ZhiPuAIService;
import com.zhipu.oapi.ClientV4;
import com.zhipu.oapi.Constants;
import com.zhipu.oapi.service.v4.model.ChatCompletionRequest;
import com.zhipu.oapi.service.v4.model.ChatMessage;
import com.zhipu.oapi.service.v4.model.ModelApiResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@Slf4j
@Component
public class ZhiPuAIServiceImpl implements ZhiPuAIService {

    @Resource
    private ClientV4 clientV4;

//    public String doChat(ChatMessage chatMessage) {
//        List<ChatMessage> messages = new ArrayList<>();
//        if (chatMessage == null) {
//            throw new RuntimeException();
//        }
//        messages.add(chatMessage);
//        ChatCompletionRequest chatCompletionRequest = ChatCompletionRequest.builder()
//                .model("glm-4-flash")
//                .stream(Boolean.FALSE)
//                .invokeMethod(Constants.invokeMethod)
//                .messages(messages)
//                .build();
//        ModelApiResponse invokeModelApiResp = clientV4.invokeModelApi(chatCompletionRequest);
//        String result = invokeModelApiResp.getData().getChoices().get(0).getMessage().getContent().toString();
//        log.info("ZhiPuAI Response: {}", result);
//        return result;
//    }

    @Override
    public String doChat(ChatMessage chatMessage) {

        List<ChatMessage> messages = new ArrayList<>();
        if (chatMessage == null) {
            throw new RuntimeException("Chat message cannot be null");
        }
        messages.add(chatMessage);
        ChatCompletionRequest chatCompletionRequest = ChatCompletionRequest.builder()
                .model("glm-4-flash")
                .stream(Boolean.FALSE)
                .invokeMethod(Constants.invokeMethod)
                .messages(messages)
                .build();

        ModelApiResponse invokeModelApiResp = clientV4.invokeModelApi(chatCompletionRequest);

        // Get the AI response
        String result = (String) invokeModelApiResp.getData().getChoices().get(0).getMessage().getContent();
        log.debug("ZhiPuAI Response: {}", result);

        return result; // 这里返回的是 AI 的响应内容
    }
}

